import { DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import {
	SortableContext,
	arrayMove,
	useSortable,
	verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import React, { useState, useEffect } from 'react';
import { Table } from 'antd';
const Row = (props) => {
	const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
		id: props['data-row-key'],
	});
	const style = {
		...props.style,
		transform: CSS.Transform.toString(
			transform && {
				...transform,
				scaleY: 1,
			},
		),
		transition,
		cursor: 'move',
		...(isDragging
			? {
				position: 'relative',
				zIndex: 9999,
			}
			: {}),
	};
	return <tr {...props} ref={setNodeRef} style={style} {...attributes} {...listeners} />;
};
const Sortable = ({
	columns,
	dataSource,
	onRowChange,
	...props
}) => {

	const [data, setData] = useState(dataSource);

	useEffect(() => {
		setData(dataSource);
	}, [dataSource]);

	const sensors = useSensors(
		useSensor(PointerSensor, {
			activationConstraint: {
				distance: 1,
			},
		}),
	);

	const onDragEnd = ({ active, over }) => {
		console.log(active, over)
		if (active.id !== over?.id) {
			setData((prev) => {
				const activeIndex = prev.findIndex((i) => i.key === active.id);
				const overIndex = prev.findIndex((i) => i.key === over?.id);
				return arrayMove(prev, activeIndex, overIndex);
			});
		}
		onRowChange({ active, over })
	};

	return (
		<DndContext sensors={sensors} modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
			<SortableContext
				// rowKey array
				items={data.map((i) => i.key)}
				strategy={verticalListSortingStrategy}
			>
				<Table
					components={{
						body: {
							row: Row,
						},
					}}
					rowKey="key"
					columns={columns}
					dataSource={data}
				/>
			</SortableContext>
		</DndContext>
	);
};
export default Sortable;